// pages/profile/index.js
const app = getApp()
const api = app.api
const wxutil = app.wxutil

Page({
  data: {
    user: {},
  }, 
  onLoad: function () {
  },
  onShow() {
    this.getUser()
    const userId = this.data.user.id
    if (!userId) {
      // 数据初始化
      this.setData({
      })
    }
    var that=this;

    wx.request({
      url: app.globalData.urlHome + '/user/getUserData',
      data: {
        "openid": app.globalData.openid
      },
      header: {
        "accept": "*/*",
        "content-type": "application/json",
        'Authorization':app.globalData.token
      },
      method: "POST",
      success(res) {
        var userInfo=res.data;
        var isGuider;
        if(userInfo.role==1)isGuider=true;
        else if(userInfo.role==0) isGuider=false;
        // console.log(userInfo);

        that.setData({
          isGuider:isGuider,
          score:userInfo.score
        })
        console.log("get user data success!");
        //console.log(userInfo);
        if(isGuider==true){
          that.setData({
            status:'已认证'
          })
        }
      }
    })
  },

  Encoder: function (str) {
    var res = "";
    for (var i = 0; i < str.length; i++) {
      if (str[i] == '&') {
        res += '#';
      } else {
        res += str[i];
      }
    }
    return res;
  },

  /**
   * 获取用户信息
   */
  getUser() {
    let userDetail = app.globalData.userDetail
    // 授权用户使用userDetail作为用户信息
    if (userDetail) {
      const userId = userDetail.id
      const url = api.userAPI + userId + "/"
      
      wxutil.request.get(url).then((res) => {
        if (res.data.code == 200) {
          // 更新缓存
          const user = res.data.data
          userDetail = Object.assign(userDetail, user)
          wxutil.setStorage("userDetail", userDetail)
          app.globalData.userDetail = userDetail
          this.setData({
            isAuth: true,
            user: userDetail
          })

          const tabIndex = this.data.tabIndex
          if (tabIndex == 0) {
            this.getTopics(userId)
          }
          if (tabIndex == 1) {
            this.getComments(userId)
          }
          if (tabIndex == 2) {
            this.getStars(userId)
          }
        }
      })
    }
  },

})